﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CQRS.Infrastructure.Hermes.Infrastructure.ServiceLocator;
using CQRS.Reports;
using CQRS.Sample.Domain.ReportDtos;

namespace CQRS.Example.SampleApplication.Views
{
    public partial class PlanesForm : BaseForm
    {
        private readonly IReportingRepository _reportingRepository;

        public PlanesForm(IReportingRepository reportingRepository)
        {
            InitializeComponent();
            _reportingRepository = reportingRepository;
            RefreshPlanesGrid();
        }

        private void buttonAddPlane_Click(object sender, EventArgs e)
        {
            var planeDetailsForm = IoC.Resolve<PlaneDetailsForm>();
            LoadDialog(planeDetailsForm);
            RefreshPlanesGrid();
        }

        private void RefreshPlanesGrid()
        {
            IEnumerable<PlaneReport> planeReports = _reportingRepository.GetByCriteria<PlaneReport>(null);
            dataGridViewPlanes.Rows.Clear();
            dataGridViewPlanes.Refresh();
            foreach (PlaneReport planeReport in planeReports)
            {
                dataGridViewPlanes.Rows.Add(planeReport.Id, planeReport.PlaneName, planeReport.Manufacturer,
                                            planeReport.HasBeenRepaired, planeReport.HasCrashed, "...");
            }
        }

        private void dataGridViewPlanes_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((e.ColumnIndex == 5) && (e.RowIndex >= 0))
            {
                object planeId = dataGridViewPlanes.Rows[e.RowIndex].Cells["Id"].Value;
                PlaneDetailsReport planeDetailsReport =
                    _reportingRepository
                        .GetByCriteria<PlaneDetailsReport>(new QueryCriteria().AddCriteria("Id", planeId))
                        .First();
                var planeDetailsForm = IoC.Resolve<PlaneDetailsForm>();
                planeDetailsForm.FillWithReport(planeDetailsReport);
                LoadDialog(planeDetailsForm);
                RefreshPlanesGrid();
            }
        }
    }
}